package ch3.stack.sq;

public class Exam3_4 {
    public static boolean isMatch(String str) { //例3.4的算法
        SqStackClass<Character> st = new SqStackClass<>(); //建立一个顺序栈
        for (int i = 0; i < str.length(); i++) {
            char e = str.charAt(i);
            if (e == '(' || e == '[' || e == '{') {
                st.push(e);             //将左括号进栈
            } else {
                if (e == ')') {
                    if (st.empty() || st.peek() != '(') {   //栈空或栈顶不是匹配的'('返回false
                        return false;
                    }
                    st.pop();
                } else if (e == ']') {
                    if (st.empty() || st.peek() != '[') {
                        return false;       //栈空或栈顶不是匹配的'['返回false
                    }
                    st.pop();
                } else if (e == '}') {
                    if (st.empty() || st.peek() != '{') {
                        return false;       //栈空或栈顶不是匹配的'{'返回false
                    }
                    st.pop();
                }
            }
        }
        return st.empty();
    }

    public static void main(String[] args) {
        System.out.println("测试1");
        String str = "([)]";
        if (isMatch(str)) {
            System.out.println(str + "中括号是匹配的");
        } else {
            System.out.println(str + "中括号不匹配");
        }

        System.out.println("测试2");
        str = "([])";
        if (isMatch(str)) {
            System.out.println(str + "中括号是匹配的");
        } else {
            System.out.println(str + "中括号不匹配");
        }
    }
} 
